#include "log.h"
#include "ui_log.h"
#include "card.h"
#include "bill.h"
#include "widget.h"
#include <QTextCodec>
Log::Log(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Log)
{
    ui->setupUi(this);
}

Log::~Log()
{
    delete ui;
}

void Log::setWidget(Widget *w)
{
    widget = w;
}

void Log::setCard(Card *c)
{
    card = c;
}
void Log::setBill(Bill *b)
{
    bill = b;
}

void Log::setNetworkManager(NetworkManager *manager)
{
    networkManager = manager;
}
void Log::on_pushButton_home_clicked()
{
    widget->show();
    this->hide();
}
void Log::on_pushButton_card_clicked()
{
    card->show();
    this->hide();
}

void Log::on_pushButton_bill_clicked()
{
    bill->show();
    this->hide();
}
//点击刷新按钮，发送查看车辆信息指令
void Log::on_pushButton_check_car_clicked()
{
    QByteArray dataToSend = "IN_STORE_VEHICLE|check|";
    networkManager->sendData(dataToSend);
    //调试
    qDebug() << "Sent data: " << dataToSend;
}

// 处理接收到的数据
void Log::onDataReceived(const QByteArray &data)
{
        QString receivedData;
        // 先尝试使用 UTF - 8 解码
        QTextCodec *utf8Codec = QTextCodec::codecForName("UTF-8");
        receivedData = utf8Codec->toUnicode(data);

        QStringList parts = receivedData.split('|'); // 按 '|' 分割字符串
        int car_informationIndex = parts.indexOf("IN_STORE_VEHICLE");

        if (car_informationIndex != -1)
        {
            isReceivingCarInfo = true;
            carCsvData.clear();
        }
        else if (isReceivingCarInfo)
        {
            carCsvData.append(receivedData);
            // 假设每次接收数据后检查是否数据完整，这里简单以换行符判断
            if (receivedData.contains('\n'))
            {
                isReceivingCarInfo = false;
                QStringList lines = carCsvData.split('\n');
                if (lines.size() > 0)
                {
                    QStringList headers = lines[0].split(',');
                    // 设置表格列数
                    ui->tableWidget->setColumnCount(headers.size());
                    // 设置表头
                    ui->tableWidget->setHorizontalHeaderLabels(headers);

                    // 设置表格行数
                    ui->tableWidget->setRowCount(lines.size() - 1);

                    for (int i = 1; i < lines.size(); ++i)
                    {
                        QString line = lines[i].trimmed();
                        if (!line.isEmpty())
                        {
                            QStringList fields = line.split(',');
                            for (int j = 0; j < fields.size(); ++j)
                            {
                                QTableWidgetItem *item = new QTableWidgetItem(fields[j]);
                                ui->tableWidget->setItem(i - 1, j, item);
                            }
                        }
                    }
                }
                carCsvData.clear();
            }
        }
}




